package com.ks3.demo.main;

import static com.ks3.demo.main.Constants.DST_BUCKETNAME;
import static com.ks3.demo.main.Constants.DST_OBJECTKEY;
import static com.ks3.demo.main.Constants.END_POINT;
import static com.ks3.demo.main.Constants.SRC_BUCKETNAME;
import static com.ks3.demo.main.Constants.SRC_OBJECTKEY;
import static com.ks3.demo.main.Constants.TEST_MULTIUPLOAD_FILE;

import android.app.AlertDialog.Builder;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.ks3.demo.main.BucketInpuDialog.OnBucketDialogListener;
import com.ks3.demo.main.BucketObjectInpuDialog.OnBucketObjectDialogListener;
import com.ksyun.ks3.exception.Ks3ClientException;
import com.ksyun.ks3.exception.Ks3ServiceException;
import com.ksyun.ks3.model.Bucket;
import com.ksyun.ks3.model.BucketQuota;
import com.ksyun.ks3.model.Ks3ObjectSummary;
import com.ksyun.ks3.model.ObjectListing;
import com.ksyun.ks3.model.ObjectMetadata;
import com.ksyun.ks3.model.Part;
import com.ksyun.ks3.model.PartETag;
import com.ksyun.ks3.model.PostObjectFormFields;
import com.ksyun.ks3.model.acl.CannedAccessControlList;
import com.ksyun.ks3.model.result.AbortMultipartUploadResult;
import com.ksyun.ks3.model.result.CompleteMultipartUploadResult;
import com.ksyun.ks3.model.result.CopyObjectResult;
import com.ksyun.ks3.model.result.CreateBucketResult;
import com.ksyun.ks3.model.result.DeleteBucketPolicyResult;
import com.ksyun.ks3.model.result.DeleteBucketQuotaResult;
import com.ksyun.ks3.model.result.DeleteBucketReplicationResult;
import com.ksyun.ks3.model.result.DeleteBucketResult;
import com.ksyun.ks3.model.result.DeleteObjectResult;
import com.ksyun.ks3.model.result.DeleteObjectTaggingResult;
import com.ksyun.ks3.model.result.GetBucketACLResult;
import com.ksyun.ks3.model.result.GetBucketPolicyResult;
import com.ksyun.ks3.model.result.GetBucketQuotaResult;
import com.ksyun.ks3.model.result.GetBucketReplicationResult;
import com.ksyun.ks3.model.result.GetObjectACLResult;
import com.ksyun.ks3.model.result.GetObjectAdpResult;
import com.ksyun.ks3.model.result.GetObjectResult;
import com.ksyun.ks3.model.result.GetObjectTaggingResult;
import com.ksyun.ks3.model.result.HeadBucketResult;
import com.ksyun.ks3.model.result.HeadObjectResult;
import com.ksyun.ks3.model.result.InitiateMultipartUploadResult;
import com.ksyun.ks3.model.result.Ks3Result;
import com.ksyun.ks3.model.result.ListBucketsResult;
import com.ksyun.ks3.model.result.ListObjectsResult;
import com.ksyun.ks3.model.result.ListPartsResult;
import com.ksyun.ks3.model.result.PutBucketACLResult;
import com.ksyun.ks3.model.result.PutBucketPolicyResult;
import com.ksyun.ks3.model.result.PutBucketQuotaResult;
import com.ksyun.ks3.model.result.PutBucketReplicationResult;
import com.ksyun.ks3.model.result.PutObjectACLResult;
import com.ksyun.ks3.model.result.PutObjectAdpResult;
import com.ksyun.ks3.model.result.PutObjectFetchResult;
import com.ksyun.ks3.model.result.PutObjectResult;
import com.ksyun.ks3.model.result.PutObjectTaggingResult;
import com.ksyun.ks3.model.ReplicationRule;
import com.ksyun.ks3.model.result.UploadPartResult;
import com.ksyun.ks3.services.Ks3Client;
import com.ksyun.ks3.services.Ks3ClientConfiguration;
import com.ksyun.ks3.services.MultiUploader;
import com.ksyun.ks3.services.handler.AbortMultipartUploadResponseHandler;
import com.ksyun.ks3.services.handler.CompleteMultipartUploadResponseHandler;
import com.ksyun.ks3.services.handler.CopyObjectResponseHandler;
import com.ksyun.ks3.services.handler.CreateBucketResponseHandler;
import com.ksyun.ks3.services.handler.DeleteBucketPolicyResponseHandler;
import com.ksyun.ks3.services.handler.DeleteBucketQuotaResponseHandler;
import com.ksyun.ks3.services.handler.DeleteBucketReplicationResponseHandler;
import com.ksyun.ks3.services.handler.DeleteBucketResponseHandler;
import com.ksyun.ks3.services.handler.DeleteObjectResponseHandler;
import com.ksyun.ks3.services.handler.DeleteObjectTaggingResponseHandler;
import com.ksyun.ks3.services.handler.GetBucketACLResponseHandler;
import com.ksyun.ks3.services.handler.GetBucketPolicyResponseHandler;
import com.ksyun.ks3.services.handler.GetBucketQuotaResponseHandler;
import com.ksyun.ks3.services.handler.GetBucketReplicationResponseHandler;
import com.ksyun.ks3.services.handler.GetObjectACLResponseHandler;
import com.ksyun.ks3.services.handler.GetObjectAdpResponseHandler;
import com.ksyun.ks3.services.handler.GetObjectResponseHandler;
import com.ksyun.ks3.services.handler.GetObjectTaggingResponseHandler;
import com.ksyun.ks3.services.handler.HeadBucketResponseHandler;
import com.ksyun.ks3.services.handler.HeadObjectResponseHandler;
import com.ksyun.ks3.services.handler.InitiateMultipartUploadResponseHandler;
import com.ksyun.ks3.services.handler.ListBucketsResponseHandler;
import com.ksyun.ks3.services.handler.ListObjectsResponseHandler;
import com.ksyun.ks3.services.handler.ListPartsResponseHandler;
import com.ksyun.ks3.services.handler.PutBucketACLResponseHandler;
import com.ksyun.ks3.services.handler.PutBucketPolicyResponseHandler;
import com.ksyun.ks3.services.handler.PutBucketQuotaResponseHandler;
import com.ksyun.ks3.services.handler.PutBucketReplicationResponseHandler;
import com.ksyun.ks3.services.handler.PutObjectACLResponseHandler;
import com.ksyun.ks3.services.handler.PutObjectAdpResponseHandler;
import com.ksyun.ks3.services.handler.PutObjectFetchResponseHandler;
import com.ksyun.ks3.services.handler.PutObjectResponseHandler;
import com.ksyun.ks3.services.handler.PutObjectTaggingResponseHandler;
import com.ksyun.ks3.services.handler.UploadPartResponseHandler;
import com.ksyun.ks3.services.request.AbortMultipartUploadRequest;
import com.ksyun.ks3.services.request.CompleteMultipartUploadRequest;
import com.ksyun.ks3.services.request.CopyObjectRequest;
import com.ksyun.ks3.services.request.CreateBucketRequest;
import com.ksyun.ks3.services.request.DeleteBucketPolicyRequest;
import com.ksyun.ks3.services.request.DeleteBucketQuotaRequest;
import com.ksyun.ks3.services.request.DeleteBucketReplicationRequest;
import com.ksyun.ks3.services.request.DeleteBucketRequest;
import com.ksyun.ks3.services.request.DeleteObjectRequest;
import com.ksyun.ks3.services.request.GetBucketACLRequest;
import com.ksyun.ks3.services.request.GetBucketPolicyRequest;
import com.ksyun.ks3.services.request.GetBucketQuotaRequest;
import com.ksyun.ks3.services.request.GetBucketReplicationRequest;
import com.ksyun.ks3.services.request.GetObjectACLRequest;
import com.ksyun.ks3.services.request.GetObjectRequest;
import com.ksyun.ks3.services.request.HeadBucketRequest;
import com.ksyun.ks3.services.request.HeadObjectRequest;
import com.ksyun.ks3.services.request.InitiateMultipartUploadRequest;
import com.ksyun.ks3.services.request.ListBucketsRequest;
import com.ksyun.ks3.services.request.ListObjectsRequest;
import com.ksyun.ks3.services.request.ListPartsRequest;
import com.ksyun.ks3.services.request.PutBucketPolicyRequest;
import com.ksyun.ks3.services.request.PutBucketACLRequest;
import com.ksyun.ks3.services.request.PutBucketQuotaRequest;
import com.ksyun.ks3.services.request.PutBucketReplicationRequest;
import com.ksyun.ks3.services.request.PutObjectACLRequest;
import com.ksyun.ks3.services.request.PutObjectRequest;
import com.ksyun.ks3.services.request.PutObjectFetchRequest;
import com.ksyun.ks3.services.request.UploadPartRequest;
import com.ksyun.ks3.services.request.adp.Adp;
import com.ksyun.ks3.services.request.adp.GetObjectAdpRequest;
import com.ksyun.ks3.services.request.adp.PutObjectAdpRequest;
import com.ksyun.ks3.services.request.tag.DeleteObjectTaggingRequest;
import com.ksyun.ks3.services.request.tag.GetObjectTaggingRequest;
import com.ksyun.ks3.services.request.tag.ObjectTagging;
import com.ksyun.ks3.services.request.tag.PutObjectTaggingRequest;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Headers;

/**
 * 包含一系列资源管理操作Api使用示例
 */
public class MainActivity extends AppCompatActivity {

    // Bucket
    public static final int LIST_BUCKETS = 0;
    public static final int CREATE_BUCKET = 1;
    public static final int GET_BUCKET_ACL = 2;
    public static final int PUT_BUCKET_ACL = 3;
    public static final int HEAD_BUCKET = 4;
    public static final int DELETE_BUCKET = 5;
    public static final int PUT_BUCKET_CRR = 18;
    public static final int PUT_BUCKET_POLICY = 19;
    public static final int PUT_BUCKET_QUOTA = 20;
    // Object
    public static final int GET_OBJECT = 6;
    public static final int HEAD_OBJECT = 7;
    public static final int PUT_OBJECT = 8;
    public static final int DELETE_OBJECT = 9;
    public static final int GET_OBJECT_ACL = 10;
    public static final int PUT_OBJECT_ACL = 11;
    public static final int LIST_OBJECTS = 12;
    public static final int COPY_OBJECT = 17;
    public static final int PUT_OBJECT_ADP = 21;
    public static final int FETCH_OBJECT = 23;
    public static final int POST_OBJECT = 24;
    public static final int GET_BUCKET_POLICY = 25;
    public static final int DELETE_BUCKET_POLICY = 26;
    public static final int GET_BUCKET_CRR = 27;
    public static final int DELETE_BUCKET_CRR = 28;

    // Upload
    public static final int UPLOAD = 13;
    // Download
    public static final int DOWNLOAD = 14;
    public static final int LIST_PART = 15;
    public static final int MultiPartUpload = 16;
    public static final int GET_OBJECT_ASYNC = 29;
    public static final int MULTI_UPLOAD = 30;
    public static final int MULTI_UPLOAD_EXAMPLE = 31;
    public static final int PUT_OBJECT_TAG = 32;
    public static final int GET_OBJECT_TAG = 33;
    public static final int DELETE_OBJECT_TAG = 34;
    public static final int PUT_OBJECT_SYNC = 35;
    private static final String API = "api";
    private static final String RESULT = "result";
    private Ks3ClientConfiguration configuration;
    private Ks3Client client;
    private TextView resultTv;
    private ListView commandList;
    private String[] command_array;
    private Builder bucketDialogBuilder;
    private BucketInpuDialog bucketInpuDialog;
    private BucketObjectInpuDialog bucketObjectInpuDialog;
    private BucketCopyObjectInpuDialog bucketCopyObjectInpuDialog;

    private Map<String, Integer> viewListData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dummy);
        setUpKs3Client();
        setUpUserInterface();
        PermissionUtils.permission(PermissionConstants.STORAGE).callback(new PermissionUtils.SimpleCallback() {
            @Override
            public void onGranted() {

            }

            @Override
            public void onDenied() {

            }
        }).request();
    }

    private Map<String, Integer> getViewListData(String[] source) {
        HashMap<String, Integer> result = new LinkedHashMap<>();
        if (source.length <= 0) return result;
        for (String str : source) {
            String[] split = str.split(":");
            result.put(split[0], new Integer(split[1]));
        }
        return result;
    }

    private void setUpUserInterface() {
        bucketCopyObjectInpuDialog = new BucketCopyObjectInpuDialog(MainActivity.this);
        bucketInpuDialog = new BucketInpuDialog(MainActivity.this);
        bucketObjectInpuDialog = new BucketObjectInpuDialog(MainActivity.this);
        commandList = (ListView) findViewById(R.id.command_list);
        command_array = getResources().getStringArray(R.array.command_array);
        viewListData = getViewListData(command_array);
        commandList.setAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, viewListData.keySet().toArray(new String[viewListData.keySet().size()])));
        commandList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int position, long arg3) {
                TextView view = (TextView) arg1;
                String text = (String) view.getText();
                Integer pos = viewListData.get(text);
                System.out.println("开始执行: " + text + " 位置：" + pos);
                switch (pos) {
                    case UPLOAD:
                        Intent intent_upload = new Intent(MainActivity.this,
                                UploadActivity.class);
                        startActivity(intent_upload);
                        break;
                    case DOWNLOAD:
                        Intent intent_download = new Intent(MainActivity.this,
                                DownloadActivity.class);
                        startActivity(intent_download);
                        break;
                    case LIST_BUCKETS:
                        listBuckets();
                        break;
                    case CREATE_BUCKET:
                        createBucket();
                        break;
                    case GET_BUCKET_ACL:
                        getBucketACL();
                        break;
                    case PUT_BUCKET_ACL:
                        putBucketACL();
                        break;
                    case HEAD_BUCKET:
                        headBucket();
                        break;
                    case DELETE_BUCKET:
                        deleteBucket();
                        break;
                    case GET_OBJECT:
                        getObject();
                        break;
                    case HEAD_OBJECT:
                        headObject();
                        break;
                    case PUT_OBJECT:
                        putObject();
                        break;
                    case DELETE_OBJECT:
                        deleteObject();
                        break;
                    case GET_OBJECT_ACL:
                        getObjectACL();
                        break;
                    case PUT_OBJECT_ACL:
                        putObjectACL();
                        break;
                    case LIST_OBJECTS:
                        listObjects();
                        break;
                    case MULTI_UPLOAD:
                        multipartUpload();
                        break;
                    case MULTI_UPLOAD_EXAMPLE:
                        multipartUploadExample();
                        break;
                    case MultiPartUpload:
                        Intent multi_upload = new Intent(MainActivity.this,
                                MultiUploadActivity.class);
                        startActivity(multi_upload);
                        break;
                    case COPY_OBJECT:
                        copyObject();
                        break;
                    case PUT_BUCKET_CRR:
                        putBucketCrr();
                        break;
                    case GET_BUCKET_CRR:
                        getBucketCrr();
                        break;
                    case DELETE_BUCKET_CRR:
                        deleteBucketCrr();
                        break;
                    case PUT_BUCKET_QUOTA:
                        putBucketQuota();
                        getBucketQuota();
                        deleteBucketQuota();
                        break;
                    case PUT_BUCKET_POLICY:
                        putBucketPolicy();
                        break;
                    case GET_BUCKET_POLICY:
                        getBucketPolicy();
                        break;
                    case DELETE_BUCKET_POLICY:
                        deleteBucketPolicy();
                        break;
                    case PUT_OBJECT_ADP:
                        testPutAndQueryAdp();
                        break;
                    case FETCH_OBJECT:
                        putObjectFetch();
                        break;
                    case POST_OBJECT:
                        postObject();
                        break;
                    case GET_OBJECT_ASYNC:
                        getObjectAsync();
                        break;
                    case PUT_OBJECT_TAG:
                        putObjectTag();
                        break;
                    case GET_OBJECT_TAG:
                        getObjectTag();
                        break;
                    case DELETE_OBJECT_TAG:
                        deleteObjectTag();
                        break;
                    case PUT_OBJECT_SYNC:
                        putObjectSync();
                        break;
                    default:
                        break;
                }
            }

        });
    }

    private void copyObject() {
        final String apiName = "Copy Object";
        CopyObjectRequest copyObjectRequest = new CopyObjectRequest(DST_BUCKETNAME, DST_OBJECTKEY, SRC_BUCKETNAME, SRC_OBJECTKEY);
        client.copyObject(copyObjectRequest, new CopyObjectResponseHandler() {
            @Override
            public void onFailure(CopyObjectRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }

            @Override
            public void onSuccess(CopyObjectRequest request, CopyObjectResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }
        });
    }

    private void putObject() {
        final String apiName = "Put Object";
        bucketObjectInpuDialog
                .setOnBucketObjectDialogListener(new OnBucketObjectDialogListener() {
                    @Override
                    public void confirmBucketAndObject(String name, String key) {
                        File file = new File(Constants.TEST_MULTIUPLOAD_FILE);
                        PutObjectRequest request = new PutObjectRequest(name, key, file);
                        client.putObject(request, new PutObjectResponseHandler() {
                            @Override
                            public void onTaskSuccess(PutObjectRequest request, PutObjectResult result) {
                                String resultStr = resultHandler(apiName, result, "");
                                toResultPage(apiName, resultStr);
                                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                            }

                            @Override
                            public void onTaskProgress(double progress) {
                                Log.d(apiName, " ---onTaskProgress---" + progress);
                            }

                            @Override
                            public void onTaskCancel() {
                                ToastUtils.showShort("任务取消");
                            }

                            @Override
                            public void onTaskFailure(PutObjectRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                                toResultPage(apiName, resultStr);
                                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                            }
                        });
                    }
                });
        bucketObjectInpuDialog.show();

    }


    private void putObjectSync() {
        final String apiName = "Put Object Sync";
        bucketObjectInpuDialog
                .setOnBucketObjectDialogListener(new OnBucketObjectDialogListener() {
                    @Override
                    public void confirmBucketAndObject(String name, String key) {
                        File file = new File(Constants.TEST_MULTIUPLOAD_FILE);
                        final PutObjectRequest request = new PutObjectRequest(name, key, file);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    PutObjectResult result = client.syncPutObject(request);
                                    String resultStr = resultHandler(apiName, result, "");
                                    toResultPage(apiName, resultStr);
                                    Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                                } catch (Ks3ClientException e) {
                                    String resultStr = exceptionHandler(apiName, e, null);
                                    toResultPage(apiName, resultStr);
                                    Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                                } catch (Ks3ServiceException e) {
                                    String resultStr = exceptionHandler(apiName, null, e);
                                    toResultPage(apiName, resultStr);
                                    Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                                }

                            }
                        }).start();
                    }
                });
        bucketObjectInpuDialog.show();
    }

    private void setUpKs3Client() {
        // AK&SK形式直接初始化，仅建议测试时使用，正式环境下请替换AuthListener方式
        client = new Ks3Client(Constants.ACCESS_KEY__ID,
                Constants.ACCESS_KEY_SECRET, MainActivity.this);
        configuration = Ks3ClientConfiguration.getDefaultConfiguration();
        configuration.setPathStyleAccess(false);
        configuration.setSocketTimeout(10000);
        client.setEndpoint("ks3-cn-beijing.ksyuncs.com");
        client.setConfiguration(configuration);

//        Authorization authorization  = new Authorization(Constants.ACCESS_KEY__ID, Constants.ACCESS_KEY_SECRET);
//        client = new Ks3Client(authorization, this);
//        client = Ks3ClientFactory.getDefaultClient(this);
//        client.setConfiguration(configuration);
//        client.setEndpoint(Constants.END_POINT);
//        configuration.setPathStyleAccess(true);
        // AuthListener方式初始化
//        client = new Ks3Client(new AuthListener() {
//            @Override
//            public String onCalculateAuth(final String httpMethod,
//                                          final String ContentType, final String Date,
//                                          final String ContentMD5, final String Resource,
//                                          final String Headers) {
//                // 此处应由APP端向业务服务器发送post请求返回Token。
//                // 需要注意该回调方法运行在非主线程
//                // 此处内部写法仅为示例，开发者请根据自身情况修改
//                String result = "";
//                try {
//                    OkHttpClient client = new OkHttpClient().newBuilder().build();
//                    MediaType type = MediaType.parse("application/json");
//                    JSONObject object = new JSONObject();
//                    object.put("http_method", httpMethod.toString());
//                    object.put("content_type", ContentType);
//                    object.put("date", Date);
//                    object.put("content_md5", ContentMD5);
//                    object.put("resource", Resource);
//                    object.put("headers", Headers);
//                    RequestBody body = RequestBody.create(type, object.toString());
//                    Request request = new Request.Builder().url("http://10.231.135.222:8000/").method("POST", body)
//                            .addHeader("Content-Type","application/json").build();
//                    Response response = client.newCall(request).execute();
//                    result = response.body().string();
//                } catch (Exception e) {
//                    Log.e(apiName, "onCalculateAuth error：" + e.toString());
//                }
//                Log.d("tag", "onCalculateAuth from server result：" + result);
//                return result;
//            }
//        }, MainActivity.this);
//        client.setEndpoint(Constants.END_POINT);
//        client.setConfiguration(configuration);

    }

    //这块有疑问，没进行操作
    protected void getObject() {
        Toast.makeText(MainActivity.this, "Please See Download Activity",
                Toast.LENGTH_SHORT).show();
    }

    private void headObject() {
        final String apiName = "Head Object";
        bucketObjectInpuDialog
                .setOnBucketObjectDialogListener(new OnBucketObjectDialogListener() {
                    @Override
                    public void confirmBucketAndObject(String name, String key) {
                        HeadObjectRequest request = new HeadObjectRequest(name, key);
                        client.headObject(request, new HeadObjectResponseHandler() {
                            @Override
                            public void onSuccess(HeadObjectRequest request, HeadObjectResult result) {
                                String resultStr = resultHandler(apiName, result, "");
                                toResultPage(apiName, resultStr);
                                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                            }

                            @Override
                            public void onFailure(HeadObjectRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                                toResultPage(apiName, resultStr);
                                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                            }
                        });
                    }
                });
        bucketObjectInpuDialog.show();
    }

    private void getObjectACL() {
        final String apiName = "Get Object ACL";
        bucketObjectInpuDialog
                .setOnBucketObjectDialogListener(new OnBucketObjectDialogListener() {
                    @Override
                    public void confirmBucketAndObject(String name, String key) {
                        GetObjectACLRequest request = new GetObjectACLRequest(name, key);
                        client.getObjectACL(request, new GetObjectACLResponseHandler() {
                            @Override
                            public void onSuccess(GetObjectACLRequest request, GetObjectACLResult result) {
                                String resultStr = resultHandler(apiName, result, result.getAccessControlPolicy().toString());
                                toResultPage(apiName, resultStr);
                                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                            }

                            @Override
                            public void onFailure(GetObjectACLRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                                toResultPage(apiName, resultStr);
                                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                            }
                        });
                    }
                });
        bucketObjectInpuDialog.show();
    }

    private void deleteBucket() {
        final String apiName = "Delete Bucket";

        bucketInpuDialog.setOnBucketInputListener(new OnBucketDialogListener() {
            @Override
            public void confirmBucket(String name) {
                DeleteBucketRequest request = new DeleteBucketRequest(name);
                client.deleteBucket(request, new DeleteBucketResponseHandler() {
                    @Override
                    public void onSuccess(DeleteBucketRequest request, DeleteBucketResult result) {
                        String resultStr = resultHandler(apiName, result, "");
                        toResultPage(apiName, resultStr);
                        Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                    }

                    @Override
                    public void onFailure(DeleteBucketRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                        String resultStr = exceptionHandler(apiName, clientException, serviceException);
                        toResultPage(apiName, resultStr);
                        Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                    }
                });
            }
        });
        bucketInpuDialog.show();
    }

    private void putObjectACL() {
        final String apiName = "Put Object ACL";
        bucketObjectInpuDialog
                .setOnBucketObjectDialogListener(new OnBucketObjectDialogListener() {
                    @Override
                    public void confirmBucketAndObject(String name, String key) {
                        PutObjectACLRequest request = new PutObjectACLRequest(name, key);
                        request.setCannedAcl(CannedAccessControlList.PublicRead);
//                        当然也可以自行配置相关参数
//                        AccessControlList acList = new AccessControlList();
//                        GranteeId grantee = new GranteeId();
//                        grantee.setIdentifier("123456");
//                        grantee.setDisplayName("TESTTEST1");
//                        acList.addGrant(grantee, Permission.Read);
//                        GranteeId grantee1 = new GranteeId();
//                        grantee1.setIdentifier("1235789");
//                        grantee1.setDisplayName("TESTTEST1");
//                        acList.addGrant(grantee1, Permission.FullControl);
//                        request.setAccessControlList(acList);
                        client.putObjectACL(request, new PutObjectACLResponseHandler() {
                            @Override
                            public void onSuccess(PutObjectACLRequest request, PutObjectACLResult result) {
                                String resultStr = resultHandler(apiName, result, "");
                                toResultPage(apiName, resultStr);
                                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                            }

                            @Override
                            public void onFailure(PutObjectACLRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                                toResultPage(apiName, resultStr);
                                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                            }
                        });
                    }
                });
        bucketObjectInpuDialog.show();
    }

    private void headBucket() {
        final String apiName = "Head Bucket";
        bucketInpuDialog.setOnBucketInputListener(new OnBucketDialogListener() {
            @Override
            public void confirmBucket(String name) {
                HeadBucketRequest request = new HeadBucketRequest(name);
                client.headBucket(request, new HeadBucketResponseHandler() {
                    @Override
                    public void onSuccess(HeadBucketRequest request, HeadBucketResult result) {
                        String resultStr = resultHandler(apiName, result, "");
                        toResultPage(apiName, resultStr);
                        Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                    }

                    @Override
                    public void onFailure(HeadBucketRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                        String resultStr = exceptionHandler(apiName, clientException, serviceException);
                        toResultPage(apiName, resultStr);
                        Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                    }
                });
            }
        });
        bucketInpuDialog.show();
    }

    private void putBucketACL() {
        final String apiName = "Put Bucket ACL";
        bucketInpuDialog.setOnBucketInputListener(new OnBucketDialogListener() {
            @Override
            public void confirmBucket(String name) {
                PutBucketACLRequest request = new PutBucketACLRequest(name);
                // AccessControlList acl = new AccessControlList();
                // // GranteeUri urigrantee = GranteeUri.AllUsers;
                // // Permission permission = Permission.Read;
                //
                // GranteeEmail email = new GranteeEmail();
                // email.setEmail("guoli@gmail.com");
                // Permission permission = Permission.Read;
                // Grant g = new Grant(email, permission);
                //
                // GranteeUri uirGroup = GranteeUri.AllUsers;
                // Permission uripermission = Permission.Read;
                // Grant g1 = new Grant(uirGroup, uripermission);

                // acl.addGrant(g);
                // acl.addGrant(g1);

                // GranteeId grantee = new GranteeId() ;
                // grantee.setIdentifier("12773456");
                // grantee.setDisplayName("guoliTest222");
                // acl.addGrant(grantee, Permission.Read);

                // GranteeId grantee1 = new GranteeId() ;
                // grantee1.setIdentifier("123005789");
                // grantee1.setDisplayName("guoliTest2D2");
                // acl.addGrant(grantee1, Permission.Write);

                // request.setAccessControlList(acl) ;
                request.setCannedAcl(CannedAccessControlList.PublicRead);
                client.putBucketACL(request, new PutBucketACLResponseHandler() {
                    @Override
                    public void onSuccess(PutBucketACLRequest request, PutBucketACLResult result) {
                        String resultStr = resultHandler(apiName, result, "");
                        toResultPage(apiName, resultStr);
                        Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                    }

                    @Override
                    public void onFailure(PutBucketACLRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                        String resultStr = exceptionHandler(apiName, clientException, serviceException);
                        toResultPage(apiName, resultStr);
                        Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                    }
                });
            }
        });
        bucketInpuDialog.show();

    }

    private void getBucketACL() {
        final String apiName = "Get Bucket ACL";
        bucketInpuDialog.setOnBucketInputListener(new OnBucketDialogListener() {
            @Override
            public void confirmBucket(String name) {
                GetBucketACLRequest request = new GetBucketACLRequest(name);
                client.getBucketACL(request, new GetBucketACLResponseHandler() {
                    @Override
                    public void onSuccess(GetBucketACLRequest request, GetBucketACLResult result) {
                        String resultStr = resultHandler(apiName, result, result.getAccessControlPolicy().toString());
                        resultStr += result.getAccessControlPolicy().toString();
                        toResultPage(apiName, resultStr);
                        Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                    }

                    @Override
                    public void onFailure(GetBucketACLRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                        String resultStr = exceptionHandler(apiName, clientException, serviceException);
                        toResultPage(apiName, resultStr);
                        Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                    }
                });
            }
        });
        bucketInpuDialog.show();
    }

    private void deleteObject() {
        final String apiName = "Delete Object";
        bucketObjectInpuDialog
                .setOnBucketObjectDialogListener(new OnBucketObjectDialogListener() {
                    @Override
                    public void confirmBucketAndObject(String name, String key) {
                        DeleteObjectRequest request = new DeleteObjectRequest(name, key);
                        client.deleteObject(request, new DeleteObjectResponseHandler() {
                            @Override
                            public void onSuccess(DeleteObjectRequest request, DeleteObjectResult result) {
                                String resultStr = resultHandler(apiName, result, "");
                                toResultPage(apiName, resultStr);
                                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                            }

                            @Override
                            public void onFailure(DeleteObjectRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                                toResultPage(apiName, resultStr);
                                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                            }
                        });
                    }
                });
        bucketObjectInpuDialog.show();
    }

    private void listObjects() {
        final String apiName = "List Objects";
        bucketInpuDialog.setOnBucketInputListener(new OnBucketDialogListener() {
            @Override
            public void confirmBucket(String name) {
                ListObjectsRequest request = new ListObjectsRequest(name);
                // request.setPrefix("android_test/");
                // request.setDelimiter("/");
                client.listObjects(request, new ListObjectsResponseHandler() {
                    @Override
                    public void onSuccess(ListObjectsRequest request, ListObjectsResult result) {
                        //StringBuffer过长 oppo会报：android oppo msg's executing time is too longcopy
                        ObjectListing objectListing = result.getObjectListing();
                        StringBuilder stringBuilder = new StringBuilder();
                        List<Ks3ObjectSummary> objectSummaries = objectListing.getObjectSummaries();
                        for (int i = 0; i < objectListing.getObjectSummaries().size(); i++) {
                            stringBuilder.append(objectSummaries.get(i).getKey()).append("\n");
                        }
                        String resultStr = resultHandler(apiName, result, stringBuilder.toString());
                        toResultPage(apiName, resultStr);
                        Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                    }

                    @Override
                    public void onFailure(ListObjectsRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                        String resultStr = exceptionHandler(apiName, clientException, serviceException);
                        toResultPage(apiName, resultStr);
                        Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                    }
                });
            }
        });
        bucketInpuDialog.show();
    }

    private void listBuckets() {
        final String apiName = "List Buckets";
        ListBucketsRequest request = new ListBucketsRequest();
        client.listBuckets(request, new ListBucketsResponseHandler() {
            @Override
            public void onSuccess(ListBucketsRequest request, ListBucketsResult result) {
                List<Bucket> buckets = result.getBuckets();
                StringBuilder stringBuilder = new StringBuilder();
                for (Bucket bucket : buckets) {
                    stringBuilder.append(bucket.getName()).append("\n");
                }
                String resultStr = resultHandler(apiName, result, stringBuilder.toString());
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(ListBucketsRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    private void createBucket() {
        final String apiName = "Create Bucket";
        bucketInpuDialog.setOnBucketInputListener(new OnBucketDialogListener() {
            @Override
            public void confirmBucket(String name) {
                CreateBucketRequest request = new CreateBucketRequest(name);
                request.setCannedAcl(CannedAccessControlList.Private);
                client.createBucket(request, new CreateBucketResponseHandler() {
                    @Override
                    public void onSuccess(CreateBucketRequest request, CreateBucketResult result) {
                        String resultStr = resultHandler(apiName, result, "");
                        toResultPage(apiName, resultStr);
                        Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                    }

                    @Override
                    public void onFailure(CreateBucketRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                        String resultStr = exceptionHandler(apiName, clientException, serviceException);
                        toResultPage(apiName, resultStr);
                        Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                    }
                });
            }
        });
        bucketInpuDialog.show();
    }

    private void putBucketCrr() {
        final String apiName = "Put Bucket Crr";
        //设置规则
        ReplicationRule rule = new ReplicationRule();
        List<String> prefixList = new ArrayList<String>();
        prefixList.add("test");
        rule.setPrefixList(prefixList);
        rule.setTargetBucket(SRC_BUCKETNAME);
        rule.setRegion("BEIJING");
        rule.setDeleteMarkerStatus(false);
        PutBucketReplicationRequest request = new PutBucketReplicationRequest(SRC_BUCKETNAME, rule);
        client.putBucketCrr(request, new PutBucketReplicationResponseHandler() {
            @Override
            public void onSuccess(PutBucketReplicationRequest request, PutBucketReplicationResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(PutBucketReplicationRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    private void getBucketCrr() {
        final String apiName = "Get Bucket Crr";
        GetBucketReplicationRequest request = new GetBucketReplicationRequest(SRC_BUCKETNAME);
        client.getBucketCrr(request, new GetBucketReplicationResponseHandler() {
            @Override
            public void onSuccess(GetBucketReplicationRequest request, GetBucketReplicationResult result) {
                String resultStr = resultHandler(apiName, result, result.getReplicationRule().toString());
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(GetBucketReplicationRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    /**
     * 删除跨区域复制规则
     */
    private void deleteBucketCrr() {
        final String apiName = "Delete Bucket Crr";
        DeleteBucketReplicationRequest request = new DeleteBucketReplicationRequest(SRC_BUCKETNAME);
        client.deleteBucketCrr(request, new DeleteBucketReplicationResponseHandler() {
            @Override
            public void onSuccess(DeleteBucketReplicationRequest request, DeleteBucketReplicationResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(DeleteBucketReplicationRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    /**
     * 设置空间策略
     */
    private void putBucketPolicy() {
        final String apiName = "Put Bucket Policy";
        String policy = "{\n" +
                "  \"Statement\": [\n" +
                "    {\n" +
                "      \"Effect\": \"Allow\",\n" +
                "      \"Action\": [\n" +
                "        \"ks3:ListBucket\",\n" +
                "        \"ks3:ListBucketMultipartUploads\",\n" +
                "        \"ks3:GetObject\",\n" +
                "        \"ks3:GetObjectAcl\",\n" +
                "        \"ks3:ListMultipartUploadParts\"\n" +
                "      ],\n" +
                "      \"Principal\": {\n" +
                "        \"KSC\": [\n" +
                "          \"*\"\n" +
                "        ]\n" +
                "      },\n" +
                "      \"Resource\": [\n" +
                "        \"krn:ksc:ks3:::android-test\",\n" +
                "        \"krn:ksc:ks3:::android-test/*\"\n" +
                "      ]\n" +
                "    }\n" +
                "  ]\n" +
                "}";
        PutBucketPolicyRequest putBucketPolicyRequest = new PutBucketPolicyRequest(SRC_BUCKETNAME, policy);
        client.putBucketPolicy(putBucketPolicyRequest, new PutBucketPolicyResponseHandler() {
            @Override
            public void onSuccess(PutBucketPolicyRequest request, PutBucketPolicyResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(PutBucketPolicyRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    /**
     * 获取空间策略
     */
    private void getBucketPolicy() {
        final String apiName = "Get Bucket Policy";
        GetBucketPolicyRequest request = new GetBucketPolicyRequest(SRC_BUCKETNAME);
        client.getBucketPolicy(request, new GetBucketPolicyResponseHandler() {
            @Override
            public void onSuccess(GetBucketPolicyRequest request, GetBucketPolicyResult result) {
                String policy = result.getPolicy();
                String resultStr = resultHandler(apiName, result, policy);
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(GetBucketPolicyRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    /**
     * 删除空间策略
     */
    private void deleteBucketPolicy() {
        final String apiName = "Delete Bucket Policy";
        DeleteBucketPolicyRequest request = new DeleteBucketPolicyRequest(SRC_BUCKETNAME);
        client.deleteBucketPolicy(request, new DeleteBucketPolicyResponseHandler() {
            @Override
            public void onSuccess(DeleteBucketPolicyRequest request, DeleteBucketPolicyResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(DeleteBucketPolicyRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    /**
     * 设置桶配额
     */
    private void putBucketQuota() {
        final String apiName = "Put Bucket Quota";
        BucketQuota quota = new BucketQuota(1000000);
        PutBucketQuotaRequest request = new PutBucketQuotaRequest(SRC_BUCKETNAME, quota);
        client.putBucketQuota(request, new PutBucketQuotaResponseHandler() {
            @Override
            public void onSuccess(PutBucketQuotaRequest request, PutBucketQuotaResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(PutBucketQuotaRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    /**
     * 获取桶配额
     */
    private void getBucketQuota() {
        final String apiName = "Get Bucket Quota";
        GetBucketQuotaRequest request = new GetBucketQuotaRequest(SRC_BUCKETNAME);
        client.getBucketQuota(request, new GetBucketQuotaResponseHandler() {
            @Override
            public void onSuccess(GetBucketQuotaRequest request, GetBucketQuotaResult result) {
                String resultStr = resultHandler(apiName, result, result.getBucketQuota().toString());
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(GetBucketQuotaRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    /**
     * 删除桶配额
     */
    private void deleteBucketQuota() {
        final String apiName = "Delete Bucket Quota";
        DeleteBucketQuotaRequest request = new DeleteBucketQuotaRequest(SRC_BUCKETNAME);
        client.deleteBucketQuota(request, new DeleteBucketQuotaResponseHandler() {
            @Override
            public void onSuccess(DeleteBucketQuotaRequest request, DeleteBucketQuotaResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(DeleteBucketQuotaRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    /**
     * 音视频处理
     */
    public void testPutAndQueryAdp() {
        final String apiName = "PutAndQueryAdp";
        String srcObjectKey = "test/file1.mp4";
        String newObjectKey = "new/Upload3.mp4";
        //音视频处理
        Adp avop = new Adp();
        avop.setBucket(DST_BUCKETNAME);
        avop.setCommand("tag=avop&f=mp4&res=1080x720&vbr=1000k&abr=64k");
        avop.setKey(newObjectKey);

        //视频截图
        Adp avscrnshot = new Adp();
        avscrnshot.setBucket(DST_BUCKETNAME);
        avscrnshot.setCommand("tag=avscrnshot&ss=10&res=640x360&rotate=90");
        avscrnshot.setKey(newObjectKey);

        //视频采样截图
        Adp avsample = new Adp();
        avsample.setBucket(DST_BUCKETNAME);
        avsample.setCommand("tag=avsample&ss=5&t=30&res=640x360&rotate=90&interval=5&pattern=5oiq5Zu+LSUzZC5qcGc=");
        avsample.setKey(newObjectKey);

        //音视频切片
        Adp avm3u8 = new Adp();
        avm3u8.setBucket(DST_BUCKETNAME);
        avm3u8.setCommand("tag=avm3u8&segtime=10&abr=128k&vbr=1000k&res=1280x720");
        avm3u8.setKey(newObjectKey);

        //视频拼接
        Adp avconcat = new Adp();
        avconcat.setBucket(DST_BUCKETNAME);
        avconcat.setCommand("tag=avconcat&f=mp4&mode=1&file=" + com.ksyun.ks3.util.Base64.encode("test/file2.mp4".getBytes()));
        avconcat.setKey(newObjectKey);

        PutObjectAdpRequest adpRequest = new PutObjectAdpRequest(SRC_BUCKETNAME, srcObjectKey, Arrays.asList(avconcat));
        adpRequest.setNotifyURL(PropertiesUtils.getProperties(this).getProperty("callback.url"));

        //音视频元数据获取
        GetObjectAdpRequest request = new GetObjectAdpRequest("taskId");
        client.getAdpTask(request, new GetObjectAdpResponseHandler() {
            @Override
            public void onSuccess(GetObjectAdpRequest request, GetObjectAdpResult result) {
                String resultStr = resultHandler(apiName, result, result.getAdpTask().toString());
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(GetObjectAdpRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });

        //发送请求
        client.putAdpTask(adpRequest, new PutObjectAdpResponseHandler() {
            @Override
            public void onSuccess(PutObjectAdpRequest request, PutObjectAdpResult result) {
                String resultStr = resultHandler(apiName, result, result.getTaskId());
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(PutObjectAdpRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void postObject() {
        bucketObjectInpuDialog
                .setOnBucketObjectDialogListener(new OnBucketObjectDialogListener() {
                    @Override
                    public void confirmBucketAndObject(final String name, final String key) {
                        new Thread() {
                            @Override
                            public void run() {
                                uploadFileByPost(name, key);
                            }
                        }.start();
                    }
                });
        bucketObjectInpuDialog.show();
    }

    private void uploadFileByPost(String bucketName, String keyName) {
        final File file = new File(TEST_MULTIUPLOAD_FILE);
        String key = StringUtils.isEmpty(keyName) ? "test.jpg" : keyName;
        Map<String, String> postData = new HashMap<String, String>();
        postData.put("acl", "public-read");
        postData.put("key", key);
        List<String> unknownValueField = new ArrayList<String>();
        unknownValueField.add("name");
        PostObjectFormFields fields = client.getObjectFormFields(bucketName, file.getName(), postData, unknownValueField);
        Log.i("Post Object", "Signature: " + fields.getSignature());

        String uploadUrl = "http://" + bucketName + '.' + END_POINT;
        String end = "\r\n";
        String twoHyphens = "--";
        String boundary = "******";
        Log.d("Post Object", "Url: " + uploadUrl);
        try {
            URL url = new URL(uploadUrl);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

            DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());

            // 写入key
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"key\"" + end);
            dos.writeBytes(end);
            dos.writeBytes(key);
            dos.writeBytes(end);

            // 写入kssAccessId
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"KSSAccessKeyId\"" + end);
            dos.writeBytes(end);
            dos.writeBytes(fields.getKssAccessKeyId());
            dos.writeBytes(end);

            // 写入policy
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"Policy\"" + end);
            dos.writeBytes(end);
            dos.writeBytes(fields.getPolicy());
            dos.writeBytes(end);

            // 写入signature
            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"Signature\"" + end);
            dos.writeBytes(end);
            dos.writeBytes(fields.getSignature());
            dos.writeBytes(end);

            dos.writeBytes(twoHyphens + boundary + end);
            dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"" + end);
            dos.writeBytes(end);
            //将文件通过输入流读到Java代码中
            FileInputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[8192]; // 8k
            int count = 0;
            while ((count = fis.read(buffer)) != -1) {
                dos.write(buffer, 0, count);
            }
            fis.close();
            Log.i("Post Object", "file send to server............");
            dos.writeBytes(end);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
            dos.flush();

            //读取服务器返回结果
            int code = httpURLConnection.getResponseCode();
            Log.i("Post Object", "Status Code: " + code);
            InputStream is = null;
            if (code == 200 || code == 201 || code == 204) {
                is = httpURLConnection.getInputStream();
                ToastUtils.showShort("post上传成功~");
            } else {
                is = httpURLConnection.getErrorStream();
            }
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);

            StringBuilder stringBuilder = new StringBuilder();
            String result;
            while ((result = br.readLine()) != null) {
                stringBuilder.append(result);
            }
            Log.d("Post Object", "Result: " + stringBuilder.toString());
            is.close();
            dos.close();
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("Post Object", "Error: " + e.getMessage());
        }
    }

    public void putObjectFetch() {
        final String apiName = "Put Object Fetch";
        PutObjectFetchRequest request = new PutObjectFetchRequest(SRC_BUCKETNAME, "fetch-object.png", "https://pic.imgdb.cn/item/5f9a786f1cd1bbb86bcc04aa.png");
        client.putObjectFetch(request, new PutObjectFetchResponseHandler() {
            @Override
            public void onTaskSuccess(PutObjectFetchRequest request, PutObjectFetchResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onTaskFailure(PutObjectFetchRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void putObjectTag() {
        final String apiName = "Put Object Tagging";
        ObjectTagging objectTagging = new ObjectTagging();
        objectTagging.addObjectTag("tagA", "A");
        PutObjectTaggingRequest request = new PutObjectTaggingRequest(SRC_BUCKETNAME, SRC_OBJECTKEY, objectTagging);
        client.putObjectTag(request, new PutObjectTaggingResponseHandler() {
            @Override
            public void onSuccess(PutObjectTaggingRequest request, PutObjectTaggingResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(PutObjectTaggingRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void getObjectTag() {
        final String apiName = "Get Object Tagging";
        GetObjectTaggingRequest request = new GetObjectTaggingRequest(SRC_BUCKETNAME, SRC_OBJECTKEY);
        client.getObjectTag(request, new GetObjectTaggingResponseHandler() {
            @Override
            public void onSuccess(GetObjectTaggingRequest request, GetObjectTaggingResult result) {
                String resultStr = resultHandler(apiName, result, result.getTagging().toString());
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(GetObjectTaggingRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void deleteObjectTag() {
        final String apiName = "Delete Object Tagging";
        DeleteObjectTaggingRequest request = new DeleteObjectTaggingRequest(SRC_BUCKETNAME, SRC_OBJECTKEY);
        client.deleteObjectTag(request, new DeleteObjectTaggingResponseHandler() {
            @Override
            public void onSuccess(DeleteObjectTaggingRequest request, DeleteObjectTaggingResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(DeleteObjectTaggingRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void initiateMultipartUpload() {
        final String apiName = "Init Multipart Upload";
        InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(SRC_BUCKETNAME, "test.mp4");
        client.initiateMultipartUpload(request, new InitiateMultipartUploadResponseHandler() {
            @Override
            public void onSuccess(InitiateMultipartUploadRequest request, InitiateMultipartUploadResult result) {
                String resultStr = resultHandler(apiName, result, "uploadId: " + result.getUploadId());
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(InitiateMultipartUploadRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void uploadPart() {
        final String apiName = "Upload Part";
        UploadPartRequest request = new UploadPartRequest(SRC_BUCKETNAME, "test.mp4", "uploadId", new File(TEST_MULTIUPLOAD_FILE), 1024, 1, 1024);
        client.uploadPart(request, new UploadPartResponseHandler() {
            @Override
            public void onSuccess(UploadPartRequest request, UploadPartResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onTaskProgress(double progress) {
                Log.d(apiName, " ---onTaskProgress---" + progress);
            }

            @Override
            public void onFailure(UploadPartRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void listParts() {
        final String apiName = "List Parts";
        ListPartsRequest request = new ListPartsRequest(SRC_BUCKETNAME, "test.mp4", "uploadId");
        client.listParts(request, new ListPartsResponseHandler() {
            @Override
            public void onSuccess(ListPartsRequest request, ListPartsResult result) {
                StringBuilder stringBuilder = new StringBuilder();
                List<Part> parts = result.getParts();
                for (Part part : parts) {
                    stringBuilder.append(part.getPartNumber()).append(" ").append(part.getETag()).append("\n");
                }
                String resultStr = resultHandler(apiName, result, stringBuilder.toString());
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(ListPartsRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void completeMultipartUpload() {
        final String apiName = "Comp Multipart Upload";
        List<PartETag> partETags = new ArrayList<PartETag>();
        CompleteMultipartUploadRequest request = new CompleteMultipartUploadRequest(SRC_BUCKETNAME, "test.mp4", "uploadId", partETags);
        client.completeMultipartUpload(request, new CompleteMultipartUploadResponseHandler() {
            @Override
            public void onSuccess(CompleteMultipartUploadRequest request, CompleteMultipartUploadResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(CompleteMultipartUploadRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void abortMultipartUpload() {
        final String apiName = "Abort Multipart Upload";
        AbortMultipartUploadRequest request = new AbortMultipartUploadRequest(SRC_BUCKETNAME, "test.mp4", "uploadId");
        client.abortMultipartUpload(request, new AbortMultipartUploadResponseHandler() {
            @Override
            public void onSuccess(AbortMultipartUploadRequest request, AbortMultipartUploadResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(AbortMultipartUploadRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
    }

    public void multipartUpload() {
        final String apiName = "Multipart Upload";
        File file = new File(Constants.TEST_MULTIUPLOAD_FILE);
        long partSize = 1024 * 1024 * 5;
        MultiUploader uploader = new MultiUploader(client, SRC_BUCKETNAME, "test", file, partSize);
        // 设置回调函数 监听是否成功
        uploader.setHandler(new CompleteMultipartUploadResponseHandler() {
            @Override
            public void onSuccess(CompleteMultipartUploadRequest request, CompleteMultipartUploadResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
            }

            @Override
            public void onFailure(CompleteMultipartUploadRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
            }
        });
        uploader.upload();
    }

    public void multipartUploadExample() {
        File file = new File(Constants.TEST_MULTIUPLOAD_FILE);
        long partSize = 1024 * 1024 * 2;
        MultipartUploadExample uploader = new MultipartUploadExample(client, SRC_BUCKETNAME, "test", file, partSize);
        uploader.upload();
    }

    public void toResultPage(String currentPage, String result) {
        Intent intent = new Intent(
                MainActivity.this,
                RESTAPITestResult.class);

        Bundle data = new Bundle();
        data.putString(RESULT, result);
        data.putString(API, currentPage + " Result");
        intent.putExtras(data);
        startActivity(intent);
    }

    public void getObjectAsync() {
        bucketObjectInpuDialog
                .setOnBucketObjectDialogListener(new OnBucketObjectDialogListener() {
                    @Override
                    public void confirmBucketAndObject(final String name, final String key) {
                        new Thread() {
                            @Override
                            public void run() {
                                getObject(name, key);
                            }
                        }.start();
                    }
                });
        bucketObjectInpuDialog.show();
    }

    public void getObject(String bucketName, final String objectKey) {
        final String apiName = "Get Object";
        GetObjectRequest request = new GetObjectRequest(bucketName, objectKey);
        File storeFolder = new File(Environment.getExternalStorageDirectory(), "ksyun_download");
        File file = new File(storeFolder, objectKey);
        client.getObject(request, new GetObjectResponseHandler(file, bucketName, objectKey) {
            @Override
            public void onSuccess(GetObjectRequest request, GetObjectResult result) {
                String resultStr = resultHandler(apiName, result, "");
                toResultPage(apiName, resultStr);
                Log.i(apiName, apiName + " ---onSuccess---" + resultStr);
                ToastUtils.showShort("下载成功");
            }

            @Override
            public void onTaskProgress(double progress) {
                Log.d(apiName, " ---onTaskProgress---" + progress);
            }

            @Override
            public void onFailure(GetObjectRequest request, Ks3ClientException clientException, Ks3ServiceException serviceException) {
                String resultStr = exceptionHandler(apiName, clientException, serviceException);
                toResultPage(apiName, resultStr);
                Log.e(apiName, apiName + " ---onFailure---" + resultStr);
                ToastUtils.showShort("下载失败");
            }

            @Override
            public void onTaskCancel() {
                ToastUtils.showShort("任务取消");
            }
        });
    }

    public String exceptionHandler(String apiName, Ks3ClientException clientException, Ks3ServiceException serviceException) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(apiName)
                .append(" Fail！\n");
        if (clientException != null) {
            stringBuilder.append("ClientException: ")
                    .append(clientException.getMessage())
                    .append("\n");
        }
        if (serviceException != null) {
            stringBuilder.append("ServiceException: ")
                    .append(serviceException.getMessage())
                    .append("\n");
        }
        return stringBuilder.toString();
    }

    public String resultHandler(String apiName, Ks3Result result, String extraStr) {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(apiName)
                .append(" Success！\n")
                .append("Result: ")
                .append("Status Code: ")
                .append(result.getStatusCode())
                .append("\n")
                .append("Request Id: ")
                .append(result.getHeaders().get("x-kss-request-id"))
                .append("\n")
                .append(extraStr);
        return stringBuilder.toString();
    }
}
